//引入express
const express = require('express')
//引入router
const router = express.Router()
//引入passport，配合possport-JWT完成对token的验证
const passport = require('passport')
//引入jsonwebToken
const jwt = require('jsonwebtoken')
//引入Schema
const Role = require('../models/Roles')

//添加角色
router.post('/role/add', passport.authenticate('jwt', { session: false }), (req, res) => {
  const roleData = req.body
  console.log(roleData)
  Role.findOne({ name: roleData.name })
    .then(roleName => {
      console.log(roleName)
      if (roleName) {  //数据库已经有这个角色的名称了
        return res.json({
          status: 400,
          msg: '创建失败，该角色已存在'
        })
      } else {
        const newRole = new Role({
          name: roleData.name
        })
        console.log(newRole)
        newRole.save().then(role => {
          res.json({
            status: 200,
            data: role,
            msg: '创建角色成功'
          })
        }).catch(err => {
          res.json(err)
        })
      }
    }).catch(err => {
      res.json(err)
    })
})

//获取角色列表
router.get('/role/list', passport.authenticate('jwt', { session: false }), (req, res) => {
  Role.find().then(roles => {
    console.log(roles)
    res.json({
      status: 200,
      data: roles,
      msg: '获取角色列表成功'
    })
  }).catch(err => {
    console.log(err)
    res.json({
      status: 400,
      msg: '获取角色列表异常，请稍后重试'
    })
  })
})

//获取角色列表带分页
router.get('/role/getAllRole', passport.authenticate('jwt', { session: false }), (req, res) => {
  const {
    pageNum,
    pageSize
  } = req.query
  Role.find().then(roles => {
    res.json({
      status: 200,
      data: pageFilter(roles, pageNum, pageSize),
      msg: '获取角色列表成功'
    })
  }).catch(err => {
    console.log(err)
    res.json({
      status: 400,
      msg: '获取角色列表异常，请稍后重试'
    })
  })
})


//根据角色id获取角色名称
router.get('/role/getRoleName', passport.authenticate('jwt', { session: false }), (req, res) => {
  const { roleId } = req.query
  console.log(req.query)
  Role.findById({ _id: roleId }).then(roles => {
    console.log(roles)
    res.json({
      status: 200,
      data: roles.name,
      msg: '获取角色列表成功'
    })
  }).catch(err => {
    console.log(err)
    res.json({
      status: 400,
      msg: '获取角色列表异常，请稍后重试'
    })
  })
})

//根据角色id获取角色权限
router.get('/role/getRoleAuth', passport.authenticate('jwt', { session: false }), (req, res) => {
  const { roleId } = req.query
  console.log(req.query)
  Role.findById({ _id: roleId }).then(roles => {
    console.log(roles)
    res.json({
      status: 200,
      data: roles,
      msg: '获取角色列表成功'
    })
  }).catch(err => {
    console.log(err)
    res.json({
      status: 400,
      msg: '获取角色列表异常，请稍后重试'
    })
  })
})

//更新角色(设置菜单权限)
router.put('/role/update', passport.authenticate('jwt', { session: false }), (req, res) => {
  const updateData = req.body
  updateData.auth_time = Date.now()
  Role.findByIdAndUpdate(
    { _id: updateData.id },
    { $set: updateData },
    { new: true }
  ).then(newRole => {
    res.json({
      status: 200,
      data: newRole,
      msg: '更新角色且设置权限成功'
    })
  }).catch(err => {
    console.log(err)
    res.json({
      status: 400,
      msg: '更新角色异常，请稍后重试'
    })
  })
})

//删除角色
router.delete('/role/delete', passport.authenticate('jwt', { session: false }), (req, res) => {
  const roleId = req.query.roleId
  console.log(roleId)
  Role.findByIdAndDelete({ _id: roleId })
    .then(doc => {
      res.json({
        status: 200,
        msg: '删除角色成功'
      })
    }).catch(err => {
      res.json({
        status: 400,
        msg: '删除角色出错了，请稍后再试'
      })
    })
})

/*
得到指定数组的分页信息对象
 */
function pageFilter (arr, pageNum, pageSize) {
  pageNum = pageNum * 1
  pageSize = pageSize * 1
  const total = arr.length
  const pages = Math.floor((total + pageSize - 1) / pageSize)
  const start = pageSize * (pageNum - 1)
  const end = start + pageSize <= total ? start + pageSize : total
  const list = []
  for (var i = start; i < end; i++) {
    list.push(arr[i])
  }

  return {
    pageNum,
    total,
    pages,
    pageSize,
    list
  }
}

//暴露
module.exports = router